/**
 * createTime: 2018/3/15 15:08
 * author: zhibin.zhao
 * description:
 */

'use strict';   //采用严格模式，支持ES6语法
const express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
const app = express();

const db = require('./db');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));

app.get('/', function (req, res) {
    res.render('index', {list: db.list(), logined: req.session.logined});
});

app.post('/add', function (req, res) {
    console.log(req);
    db.add({name: req.body.name});
    res.redirect('/');
});

app.get('/del', function (req, res) {
    let index = req.query.index;
    db.del(index);
    res.redirect('/');
});

app.post('/update', function (req, res) {
    var index = req.body.index;
    var name = req.body.name;
    db.update(index, {name});
    res.redirect('/');
});

app.get('/get/:index', function (req, res) {
    var index = req.params.index;
    var name = db.get(index);
    res.send(name);
});

app.post('/login', function (req, res) {
    let loginname = req.body.loginname;
    let password = req.body.password;

    if(loginname === 'qishon' && password === '123456'){
        req.session.logined = true;
        res.send("success");
    }else{
        res.send("error");
    }
});

app.get('/logout', function (req, res) {
    req.session.logined = false;
    res.redirect('/');
});

app.listen(3000);